<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\Records;
use app\BaseController;
use think\Request;
use app\admin\model\Xsjsdan as XsjsdanModel;
use app\lib\Excel;

class Xsjsdan extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $page = input('page',1,'intval');
        $list = XsjsdanModel::list($page);
        return show(config('status.success'),'获取列表',$list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $dataparam=$request->post();
        $param = $params = json_decode($dataparam['param'],true);
        if(empty($param)){
            return show(config('status.error'),'没有选中要结算的单据');
        }
        $xiangtong = $this->FetchRepeatMemberInArray($param);

        /*$ghgs_num = array_unique(array_column($param,'ghgs'));
        if(count($ghgs_num)>1){
            return show(config('status.error'),'您选中的销售供货公司不是同一家');
        }
        $shdw_num = array_unique(array_column($param,'shdw'));
        if(count($shdw_num)>1){
            return show(config('status.error'),'您选中的销售收货公司不是同一家!');
        }
        $pinming_num = array_unique(array_column($param,'value'));
        if(count($pinming_num)>1){
            return show(config('status.error'),'您选中的品名不是同一个!');
        }
        $fksjarr = array_column($param,'fksj');
        sort($fksjarr);
        $fksj_num = count($fksjarr);
        $data = [];
        if($fksj_num>1){
            $data['xstime'] = $fksjarr[0]."~".$fksjarr[$fksj_num-1];
        }else{
            $data['xstime'] = $fksjarr[0];
        }*/
        $result=false;
        if(!empty($xiangtong) && is_array($xiangtong)){
            foreach ($xiangtong as $k=>$v){$datat['cgid']='';$datat['xs_num']=0;$datat['xstime']='';
                foreach ($param as $key=>$item){
                    if($v['ghgs']==$item['ghgs'] && $v['shdw']==$item['shdw'] && $v['value']==$item['value']){
                        $datat['ghgs'] = $item['ghgs'];
                        $datat['shdw'] = $item['shdw'];
                        $datat['supply_name'] = $item['supply_name'];
                        $datat['receive_name'] = $item['receive_name'];
                        $datat['value'] = $item['value'];
                        $datat['product_name'] = $item['product_name'];
                        $datat['xs_num'] += $item['xssl'];
                        $datat['xs_price'] = 0;
                        $datat['total_amount'] = 0;
                        $datat['xs_contract_code'] = '';
                        $datat['cgid'] .="{$item['id']},";
                        $datat['user_name'] = $item['user_name'];
                        $datat['xstime'] .= "{$item['fksj']},";
                        //$dataalike[] = $datat;
                        unset($param[$key]);
                    }
                }
                $datat['cgid'] = trim( $datat['cgid'],','); $datat['xstime'] = trim($datat['xstime'],',');
                $result = XsjsdanModel::add($datat);
            }
        }

        if(!empty($param) && is_array($param)){
            foreach ($param as $key=>$item){
                $data['ghgs'] = $item['ghgs'];
                $data['shdw'] = $item['shdw'];
                $data['supply_name'] = $item['supply_name'];
                $data['receive_name'] = $item['receive_name'];
                $data['value'] = $item['value'];
                $data['product_name'] = $item['product_name'];
                $data['xs_num'] = $item['xssl'];
                $data['xs_price'] = 0;
                $data['total_amount'] = 0;
                $data['xs_contract_code'] = '';
                $data['xsid'] =$item['id'];
                $data['user_name'] = $item['user_name'];
                $data['xstime'] = $item['fksj'];
                $result = XsjsdanModel::add($data);
            }
        }
        if($result){
            foreach ($params as  $k=>$v){
                $record['id'] = $v['id'];
                $record['is_xsjs'] = 1;
                Records::edit($record);
            }
        }
        if($result){
            return show(config('status.success'), '操作成功!');
        }else {
            return show(config('status.error'), '操作失败!');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
        $detail = XsjsdanModel::detail($id);
        $datas = [
            [
                'title' => '销售结算单',
                'signature'=>'部门签章：',
                'rows'  => [
                    [
                        '部门签章：', ' ', ' ', '  ', '', ' ', ' ',' '
                    ],
                    [
                        '序号', '销售时间', '品名', '销售数量（吨）', '销售单价（元）', '销售金额（元）', '销售合同号','备注'
                    ],
                    [
                        "1", "{$detail['xstime']}", "{$detail['product_name']}", "{$detail['xs_num']}", "{$detail['xs_price']}", "{$detail['total_amount']}", "{$detail['xs_contract_code']}",""
                    ],
                    [
                        " ", " ", " ", " ", " ", " ", " "," "
                    ],
                    [
                        " ", " ", " ", " ", " ", " ", " "," "
                    ],
                    [
                        "合计", " ", " ", "{$detail['xs_num']}", " ", "{$detail['total_amount']}", " "," "
                    ],
                    [
                        "终端用户", "{$detail['user_name']}", " ", "", " ", "", " "," "
                    ],
                    [
                        "制表:", " ", " ", "复审:", " ", "", "制表日期:"," "
                    ]
                ]
            ]
        ];
        $excel = new Excel();
        $excel->exportExecl1($datas);exit();




        /*$result =array ( 0 => array ( 'id' => 10, 'code' => 'ITVG622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 1 => array ( 'id' => 9, 'code' => 'EOID622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 2 => array ( 'id' => 8, 'code' => 'IIOX622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 3 => array ( 'id' => 7, 'code' => 'ZDQM622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 4 => array ( 'id' => 6, 'code' => 'NCPF622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 5 => array ( 'id' => 5, 'code' => 'PCHQ622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 6 => array ( 'id' => 4, 'code' => 'WKEI622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 7 => array ( 'id' => 3, 'code' => 'SKST622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 8 => array ( 'id' => 2, 'code' => 'QZJX622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), 9 => array ( 'id' => 1, 'code' => 'RVCI622479', 'status' => 0, 'user_id' => 0, 'exchange_time' => NULL, 'price' => '100.00', 'qrcode' => '', 'create_time' => '2022-10-19 18:01:43', 'status_text' => '未领取', ), );
        //设置表格标题
        $title = [
            'code' => '兑换码',
            'status_text' => '是否兑换',
            'price' => '面值',
            'create_time' => '生成时间',
        ];
        //添加标题到数组头部
        array_unshift($result,$title);

        //根据此参数获取数据中的值，要与表格标题键名对应
        $keys = ['code','status_text','price' , 'create_time'];
        $excel->exportExcel($result,$keys,'卡密管理' . date('Y-m-d_His') . '.xlsx', [
            // 设置宽度
            'setWidth' => [
                'A' => '20',
                'B' => '20',
                'C' => '20',
                'D' => '30',
                'E' => '30',
                'F' => '30',
                'G' => '30',
                'H' => '30',
            ]
        ]);
        exit;*/
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        //
        $data = $request->post();
        $result = XsjsdanModel::edit($data);
        if($result){
            return show(config('status.success'),'操作成功');
        }else{
            return show(config('status.error'),'操作失败');
        }

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //

    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        $result = XsjsdanModel::del($id);
        if($result){
            return show(config('status.success'), '操作成功!');
        }else{
            return show(config('status.error'), '操作失败!');
        }
    }

    /**
     * 获取相同的元素
     * @param $array
     * @return array
     */
    public function FetchRepeatMemberInArray($array) {
        $len = count ($array);
        $dataxiantong = [];
        for($i = 0; $i < $len; $i ++) {
            for($j = $i + 1; $j < $len; $j ++) {
                if ($array[$i]['ghgs'] == $array [$j]['ghgs'] && $array[$i]['shdw'] == $array [$j]['shdw'] && $array[$i]['value'] == $array [$j]['value']) {
                    $dataxiantong[] = $array [$i];
                    break;
                }
            }
        }
        return $dataxiantong;
    }
}
